package com.steven.im.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.PayTask;
import com.squareup.picasso.Picasso;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.adapter.RechargeMoneyAdapter;
import com.steven.im.base.BaseActivity;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.RechargeMoneyEntity;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.net.Url;
import com.steven.im.utils.PayResult;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.TitleBuilder;
import com.steven.im.utils.ToastUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

/**
 * Created by Steven on 2019/1/10.
 */
public class RechargeActivity extends BaseActivity {
    @BindView(R.id.ll_people)
    LinearLayout llPeople;
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.rel_weichat)
    RelativeLayout relWeiChat;
    @BindView(R.id.rel_alipay)
    RelativeLayout relAliPay;
    @BindView(R.id.iv_people)
    ImageView ivPeople;//图像
    @BindView(R.id.tv_name)
    TextView tvName;//昵称
    @BindView(R.id.tv_currentMoney)
    TextView tvCurrentMoney;//当前金币
    @BindView(R.id.tv_get)
    TextView tv_get;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;//显示充值金额
    private RechargeMoneyAdapter rechargeMoneyAdapter;
    private String paymentCode;//支付方式
    private String payWay;
    @BindView(R.id.cb_wxpay)
    CheckBox cbWxpay;
    @BindView(R.id.cb_alipay)
    CheckBox cbAlipay;
    private boolean isChecked = true;//是否已经同意 用户协议
    @BindView(R.id.cb_protocol)
    ImageView cb_protocol;
    private int ALIPAY = 1;
    private String myMoney;

    @OnClick({R.id.btn_recharge, R.id.cb_protocol, R.id.tv_xieyi})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_recharge://充值 得判断 条件
                if (!isChecked) {
                    ToastUtil.showShort(this, "请先阅读用户协议！");
                } else {
                    String amount = tv_get.getText().toString();
                    if ("0".equals(amount)) {
                        ToastUtil.showShort(App.getContext(), "请选择充值金额！");
                    } else {
                        recharge(amount);
                    }
                }
                break;
            case R.id.cb_protocol://是否已经阅读用户协议
                if (isChecked) {//没有
                    cb_protocol.setImageResource(R.drawable.login_agree);
                } else {
                    cb_protocol.setImageResource(R.drawable.login_agree01);
                }
                isChecked = !isChecked;
                break;
            case R.id.tv_xieyi://支付协议
                startActivity(new Intent(RechargeActivity.this, WebActivity.class).putExtra("title", "支付协议").putExtra("url", Url.PAY_AGREEMENT));
                break;
        }
    }

    @Override
    public void setListen() {
        cbWxpay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {//选中微信支付
                    cbAlipay.setChecked(false);
                }
            }
        });
        cbAlipay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {//支付宝支付
                    cbWxpay.setChecked(false);
                }
            }
        });
    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    public int intiLayout() {
        return R.layout.activity_recharge;
    }

    @Override
    public void initView() {
        llPeople.setBackgroundColor(getResources().getColor(R.color.white));
        llMoney.setBackgroundColor(getResources().getColor(R.color.white));
        relWeiChat.setBackgroundColor(getResources().getColor(R.color.white));
        relAliPay.setBackgroundColor(getResources().getColor(R.color.white));
        new TitleBuilder(this).setTitleText("充值")
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
    }

    @Override
    public void initData() {
        myMoney = getIntent().getStringExtra("money");
        initRecharge();
    }

    //初始化充值金额
    private void setRechargeMoney(Response<BaseEntity> response) {
        JSONArray array = response.body().getResult().getJSONArray("paymentList");
        String string_1 = array.getString(0);
        String string_2 = array.getString(0);
        JSONObject fromObject = JSON.parseObject(string_1);
        JSONObject fromObject_1 = JSON.parseObject(string_2);
        String status = fromObject.getString("paymentStatus");
        if ("1".equals(status)) {
            paymentCode = fromObject.getString("paymentCode");
            cbAlipay.setChecked(true);
            cbWxpay.setChecked(false);
        } else {
            paymentCode = fromObject_1.getString("paymentCode");
            cbAlipay.setChecked(false);
            cbWxpay.setChecked(true);
        }
        String[] money = response.body().getResult().getString("rechargeAmountItems").split(",");
        final List<String> list = new ArrayList<>(Arrays.asList(money));
        List<RechargeMoneyEntity> rechargeMoneyEntityList = new ArrayList<>();
        for (String aList : list) {
            RechargeMoneyEntity rechargeMoneyEntity = new RechargeMoneyEntity();
            rechargeMoneyEntity.setMoney(aList);
            rechargeMoneyEntityList.add(rechargeMoneyEntity);
        }
        RechargeMoneyEntity rechargeMoneyEntity = new RechargeMoneyEntity();
        rechargeMoneyEntity.setMoney("其他金额");
        rechargeMoneyEntityList.add(rechargeMoneyEntity);

        rechargeMoneyAdapter = new RechargeMoneyAdapter(this, rechargeMoneyEntityList, myMoney, tv_get);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(rechargeMoneyAdapter);
    }

    //进行充值
    private void recharge(String amount) {
        if (cbWxpay.isChecked()) {
            payWay = "WeChat";
            //微信支付
        } else {
            payWay = "Alipay";
            //支付宝支付
        }
        Task.getApiService().rechage(payWay, amount).enqueue(new MyCallback<BaseEntity>(RechargeActivity.this) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    switch (payWay) {
                        case "WeChat"://微信支付
                            if (App.getWXAPI().isWXAppInstalled()) {
                                showWeChat(response.body().getResult());
                            } else {
                                ToastUtil.showShort(App.getContext(), "未安装微信或版本号太低");
                            }
                            break;
                        case "Alipay"://支付宝支付
                            showAlipay(response.body().getResult().get("alipay_order_sign") + "");
                            break;
                    }
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //调起微信支付
    private void showWeChat(final JSONObject body) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayReq request = new PayReq();
                request.appId = body.getString("appid");
                request.partnerId = body.getString("mch_id");
                request.prepayId = body.getString("prepay_id");
                request.packageValue = body.getString("package");
                request.nonceStr = body.getString("nonce_str");
                request.timeStamp = body.getString("timestamp");
                request.sign = body.getString("sign");
                App.getWXAPI().sendReq(request);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //调起支付宝支付
    private void showAlipay(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = ALIPAY;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /*
    支付宝支付
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {   //支付宝支付
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("TAG", "handleMessage: " + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(RechargeActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(RechargeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    finish();
                    break;
                }
                default:
                    break;
            }
        }
    };

    //初始化 充值页面
    private void initRecharge() {
        Task.getApiService().initRecharge().enqueue(new MyCallback<BaseEntity>(this) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    Picasso.with(App.getContext()).load(response.body().getResult().getString("userAvatar")).into(ivPeople);
                    tvName.setText(response.body().getResult().getString("userNickname"));
                    tvCurrentMoney.setText("幸运豆：" + response.body().getResult().getString("biddingCurrency") + "豆");
                    if ("".equals(myMoney) || null == myMoney) {
                        myMoney = response.body().getResult().getString("rechargeAmountItems").split(",")[0];
                    }
                    tv_get.setText(myMoney);
                    setRechargeMoney(response);
                }
            }

            @Override
            protected void onFailure(Throwable t) {
                ToastUtil.showShort(RechargeActivity.this, "请求失败！");
            }
        });
    }
}
